package com.work.formaldehyde.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.lljjcoder.style.citylist.CityListSelectActivity;
import com.lljjcoder.style.citylist.bean.CityInfoBean;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


public class AddressActivity extends Activity implements View.OnClickListener {
    private ImageView comeback;
    private RelativeLayout submit;
    private EditText name, phone, address;
    private String namestr, phonestr, addressstr, def = "0";
    private Switch mraddress;
    private String citys;
    private TextView weizhi, location_text;
    private LinearLayout check_city;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 1);
        setContentView(R.layout.activity_address);
        citys = Url.ADDRESSCITYS;
        comeback = findViewById(R.id.jiance_comeback);
        comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(AddressActivity.this))
            init();
    }

    private String namestrs, addrstr, phonestrs, defaultstr, addridstr, opentype;

    /**
     * 初始加载
     */
    public void init() {
        Intent getint = getIntent();
        opentype = getint.getStringExtra("opentype");
        weizhi = findViewById(R.id.weizhi);
        mraddress = findViewById(R.id.mraddress);
        submit = findViewById(R.id.submit);
        submit.setOnClickListener(this);
        name = findViewById(R.id.name);
        phone = findViewById(R.id.phone);
        address = findViewById(R.id.address);
        check_city = findViewById(R.id.check_city);
        check_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddressActivity.this, CityListSelectActivity.class);
                startActivityForResult(intent, CityListSelectActivity.CITY_SELECT_RESULT_FRAG);
            }
        });
        location_text = findViewById(R.id.location_text);
        mraddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b)
                    def = "1";
                else
                    def = "0";
            }
        });
        weizhi.setText(citys);
        if (opentype.equals("1")) {
            location_text.setText("编辑收货人");
            namestrs = getint.getStringExtra("name");
            name.setText(namestrs);
            addrstr = getint.getStringExtra("addr");
            address.setText(addrstr);
            phonestrs = getint.getStringExtra("phone");
            phone.setText(phonestrs);
            def = getint.getStringExtra("default");
            if (def.equals("1"))
                mraddress.setChecked(true);
            else
                mraddress.setChecked(false);
            addridstr = getint.getStringExtra("addrid");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CityListSelectActivity.CITY_SELECT_RESULT_FRAG) {
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    return;
                }
                Bundle bundle = data.getExtras();
                CityInfoBean cityInfoBean = (CityInfoBean) bundle.getParcelable("cityinfo");
                if (null == cityInfoBean) {
                    return;
                }
                citys = cityInfoBean.getName();
                weizhi.setText(citys);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jiance_comeback:
                onBackPressed();
                break;
            case R.id.submit:
                namestr = name.getText().toString();
                phonestr = phone.getText().toString();
                addressstr = address.getText().toString();
                if (!Url.USER_ID.equals(""))
                    if (namestr.equals(""))
                        ApiUtils.SetToast(AddressActivity.this, "请输入收货人名称!");
                    else if (phonestr.equals(""))
                        ApiUtils.SetToast(AddressActivity.this, "请输入收货人电话!");
                    else if (addressstr.equals(""))
                        ApiUtils.SetToast(AddressActivity.this, "请输入详细地址!");
                    else {
                        ApiUtils.windows(AddressActivity.this, submit, "添加中~~");
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                ApiUtils.closepopup();
                            }
                        }, 10000);
                        if (opentype.equals("0"))
                            okHttp_postFromParameters(0);
                        else
                            okHttp_postFromParameters(1);
                    }
                else {
                    Intent is_login = new Intent(AddressActivity.this, LoginActivity.class);
                    startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(AddressActivity.this).toBundle());
                    ApiUtils.SetToast(AddressActivity.this, "请先登录");
                }
                break;
        }
    }

    private Request request;

    private void okHttp_postFromParameters(final int id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    if (id == 0) {
                        RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("name", namestr).add("city", citys).add("addr", addressstr).add("phone", phonestr).add("default", def)
                                .build();
                        ApiUtils.SetLog("citys=" + citys);
                        request = new Request.Builder().url(Url.ADDADDRESS).post(formBody).build();
                    } else {
                        RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("logintoken", Url.LOGIN_TOKEN).add("name", namestr).add("city", citys).add("addr", addressstr).add("phone", phonestr).add("default", def).add("addrid", addridstr)
                                .build();
                        request = new Request.Builder().url(Url.ADDADDRESS).post(formBody).build();
                    }
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot1.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot1 = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        onBackPressed();
                        GetAddressActivity.isboole = true;
                        ApiUtils.SetToast(AddressActivity.this, "添加成功");
                    } else {
                        ApiUtils.SetToast(AddressActivity.this, success_Object.getString("msg"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}
